package com.qiahao.service.impl;

import com.qiahao.bean.Question;
import com.qiahao.constant.Cons;
import com.qiahao.service.VoiceService;
import com.qiahao.util.HttpUtil;
import com.qiahao.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.MapUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;


@Service
public class VoiceServiceImpl implements VoiceService {
    @Override
    public  Map<String,Object> getVoice(Question question) {
        Map<String, Object> voiceMap = new HashMap();
        String error = "";
        Map<String, Object> map = new TreeMap<>();
        map.put("app_id", Cons.VoiceAppId);
        map.put("speaker", 1);
        map.put("format", 2);
        map.put("volume", 1);
        map.put("speed", 100);
        map.put("text", question.getQuestion());
        map.put("aht", 0);
        map.put("apc", 58);
        map.put("time_stamp", HttpUtil.getTimeStamp());
        map.put("nonce_str", HttpUtil.getNonceStr());
        map.put("sign", HttpUtil.createSign("UTF-8", map));
        String url = Cons.voiceUrl;
        Map<String, Object> resultMap = HttpUtil.doPost(url, HttpUtil.getUrl(map));

        if (resultMap == null) {
            error = "文本转语音失败";
            voiceMap.put("error",error);
            return voiceMap;
        }

        int ret = (int) resultMap.get("ret");
        if (ret == 0) {

            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            voiceMap.put("speech",dataMap.get("speech").toString());

        } else {
            error = ret < 0 ? "文本转语音网络异常" : "文本转语音参数异常";
        }


        voiceMap.put("error",error);
        return voiceMap;
    }

    @Override
    public Map<String, Object> voice2Text(String speech) {
        Map<String, Object> result = new HashMap<>();
        String error = "";
        Map<String, Object> map = new TreeMap<>();
        map.put("app_id", Cons.VoiceAppId);
        map.put("time_stamp", HttpUtil.getTimeStamp());
        map.put("nonce_str", HttpUtil.getNonceStr());
        map.put("format", 2);
        map.put("speech", speech);
        map.put("rate", 8000);
        map.put("sign", HttpUtil.createSign("UTF-8", map));
        String url = Cons.Voice2TextUrl;
        Map<String, Object> resultMap = HttpUtil.doPost(url, HttpUtil.getUrl(map));

        if (resultMap == null) {
            error = "语音转文本失败";
        }

        int ret = (int) resultMap.get("ret");
        if (ret == 0) {
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            String text = (String) dataMap.get("text");
            result.put("result", text);
        } else {
            error = ret < 0 ? "文本转语音网络异常" : "文本转语音参数异常";
        }
        result.put("error", error);
        return result;
    }
}
